//
//  Radar.m
//  Speedater
//
//  Created by Ngo Thang on 12/31/11.
//  Copyright (c) 2011 __MyCompanyName__. All rights reserved.
//

#import "Radar.h"
#import "Start.h"
#import "AppDelegate.h"
#import "AppCLLocation.h"
#import "MAnnotation.h"
#import "MKMapView+ZoomLevel.h"
#import "MapOverlay.h"
#import "MapOverlayView.h"
#import "GMap.h"
#import "JSON.h"

#define ZOOM_LEVEL 14
#define degreesToRadians(x) (M_PI * (x) / 180.0)

@interface Radar (Private)

- (void)cleanup;

@end;

@implementation Radar (Private)

- (void)cleanup
{
    self.myTabBar = nil;
    self.myMKMapView = nil;
    self.myMapView = nil;
    self.updateMapButton = nil;
    self.gmapButton = nil;
    self.locationArray = nil;
    self.radarGScanImageView = nil;
    self.radarPsudoImageView = nil;
    self.radarWScanImageView = nil;
    self.friendUsername = nil;
}

@end


@implementation Radar

@synthesize myTabBar;
@synthesize myMKMapView;
@synthesize myMapView;
@synthesize updateMapButton, gmapButton;
@synthesize locationArray;
@synthesize friendUsername;
@synthesize radarGScanImageView, radarPsudoImageView, radarWScanImageView;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        [[UIApplication sharedApplication] setStatusBarHidden:YES];
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)dealloc
{
    //NSLog(@"RADAR -> dealloc");
    [self cleanup];
    [super dealloc];
}

#pragma mark - Custom notifications

- (void)fadeAnimationDidStop:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context
{    
    radarWScanImageView.hidden = TRUE;
    facing = FALSE;
}

- (void)changedCompass:(NSNotification *)noti
{
    if (facing) return;
    facing = TRUE;
    
    NSInteger degree = [(AppCLLocation *)[noti object] degreeCompass];
    
    radarWScanImageView.hidden = FALSE;
    
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:1.0];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDidStopSelector:@selector(fadeAnimationDidStop:finished:context:)];
    
    myMapView.transform = CGAffineTransformMakeRotation(-degreesToRadians(degree));
    [UIView commitAnimations];
}

#pragma mark - Custom functions

-(void)addOnGoogleMap
{
    radarPsudoImageView.hidden = TRUE;
    
    for (id annotation in myMKMapView.annotations) {
        if ([annotation isKindOfClass:[MAnnotation class]]){
            [myMKMapView removeAnnotation:annotation];
        }
    }
    
    CLLocationCoordinate2D l0 = CLLocationCoordinate2DMake(0.0, 0.0);
    
    for(NSDictionary *dict in locationArray){
        CLLocationCoordinate2D l;
        NSDictionary *location = [dict objectForKey:@"location"];
        
        l.latitude = [[location objectForKey:@"lat"] floatValue];
        l.longitude = [[location objectForKey:@"lon"] floatValue];
        
        NSString *username = [dict objectForKey:@"username"];
        NSString *myUsername = [[NSUserDefaults standardUserDefaults] stringForKey:@"username"];
        
        if ([myUsername isEqualToString:username])
        {
            l0 = l;
            [myMKMapView addAnnotation:[[[MAnnotation alloc] initWithCoordinate:l andUsername:username andIsRoot:YES] autorelease]];
            //NSLog(@"-> %@", username);
            
            if ([[NSUserDefaults standardUserDefaults] boolForKey:@"acoustic_signal"] && ([locationArray count]-1))
            {
                AppDelegate *d = [[UIApplication sharedApplication] delegate];
                if ([[dict objectForKey:@"suche"] intValue])
                    [d playTiger];
                else
                    [d playCat];
            }
        }
        else 
        {   if (!friendUsername)
        {
            [myMKMapView addAnnotation:[[[MAnnotation alloc] initWithCoordinate:l andUsername:username andIsRoot:NO] autorelease]];
            //NSLog(@"-> %@", username);
        }
        else if ([friendUsername isEqualToString:username])
        {
            [myMKMapView addAnnotation:[[[MAnnotation alloc] initWithCoordinate:l andUsername:username andIsRoot:NO] autorelease]];
            //NSLog(@"-> %@", username);
        }
        }
    }
    
    int radius = [[[NSUserDefaults standardUserDefaults] stringForKey:@"radius"] intValue];
    int zoom_level = (radius == 4500) ? 10 : ZOOM_LEVEL;
    [myMKMapView setCenterCoordinate:l0 zoomLevel:zoom_level animated:NO];
    
    MapOverlay *mapOverlayTemp = [[MapOverlay alloc] initWithType:0 andZoomLevel:zoom_level];
    mapOverlayTemp.coordinate = l0;
    [myMKMapView addOverlay:mapOverlayTemp];
    [mapOverlayTemp release];
    if (mapOverlay)
    {
        [myMKMapView removeOverlay:mapOverlay];
        mapOverlay = nil;
    }
    mapOverlay = mapOverlayTemp;
}

- (void)onRadarGScanning
{
    if (gRadian == 360) gRadian = 1;
    radarGScanImageView.transform = CGAffineTransformMakeRotation(degreesToRadians(gRadian));
    gRadian += 1;
}

- (void)updateLocation
{
    radarWScanImageView.hidden = NO;
    radarGScanImageView.hidden = NO;
    timer1 = [NSTimer scheduledTimerWithTimeInterval:0.001 target:self selector:@selector(onRadarGScanning) userInfo:nil repeats:YES];
    
    AppDelegate *d = [[UIApplication sharedApplication] delegate];
    
    //NSLog(@"GPS(%f, %f)", d.lat, d.lon);
    
    NSString *postString = [NSString stringWithFormat:@"op=loadLocationList&username=%@&radius=%d&lat=%f&lon=%f",
                            [[NSUserDefaults standardUserDefaults] stringForKey:@"username"],
                            [[[NSUserDefaults standardUserDefaults] stringForKey:@"radius"] intValue], d.lat, d.lon];
    NSData *postData = [postString dataUsingEncoding:NSUTF8StringEncoding];
    NSString *postLength = [NSString stringWithFormat:@"%d", [postString length]];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: [NSURL URLWithString:[[NSUserDefaults standardUserDefaults] stringForKey:@"url_preference"]]];
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setHTTPBody:postData];       
    [request setTimeoutInterval:60.0];
    NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    if (conn) {
        // init data    
        responseData = [[NSMutableData data ] retain];
        
        // loading
        UIWindow *theWindow = [UIApplication sharedApplication].keyWindow;
        HUD = [[MBProgressHUD alloc] initWithWindow:theWindow];
        [theWindow addSubview:HUD];
        HUD.delegate = self;
        HUD.alpha = 0.02;
        [HUD show:YES];
    }
    [conn release];
}

- (IBAction)updateMapButtonClick:(id)sender 
{
    if (friendUsername != nil) {
        [friendUsername release];
        friendUsername = nil;
    }
    [self updateLocation];
}

- (IBAction)gmapButtonClick:(id)sender
{
    GMap *gmap = [[GMap alloc] init];
    if ([friendUsername length])
        gmap.friendUsername = [[[NSString alloc] initWithString:friendUsername] autorelease];
    else
        gmap.friendUsername = nil;
    [self.navigationController pushViewController:gmap animated:YES];
    [gmap release];
}

- (void)goStart
{
    // goto Start form
    self.tabBarController.selectedIndex = 0;
    
    UINavigationController *nav1 = [self.tabBarController.viewControllers objectAtIndex:0];
    for (UIViewController *vc in nav1.viewControllers)
        if ([vc isKindOfClass:[Start class]]){
            //NSLog(@"RADAR -> popToViewController: %@", vc);
            [nav1.topViewController.navigationController popToViewController:vc animated:YES];
            return;
        }
}

- (void)goBack
{
    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"tab_isBack"];
    self.tabBarController.selectedIndex = [[NSUserDefaults standardUserDefaults] integerForKey:@"tab_one"]==1 ? 0 : [[NSUserDefaults standardUserDefaults] integerForKey:@"tab_one"];
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    //NSLog(@"RADAR -> viewDidLoad");
    [super viewDidLoad];
    
    // background
    [self.view setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"background.png"]]];
    
    // navigation title
    self.title = @"Radar";
    
    // navigation buttons
    UIButton *logoButton = [[UIButton alloc] initWithFrame:CGRectMake(0,2,35,35)];
    [logoButton setBackgroundImage:[UIImage imageNamed:@"logo.png"] forState:UIControlStateNormal];
    [logoButton addTarget:self action:@selector(goStart) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *iLButton = [[UIBarButtonItem alloc] initWithCustomView:logoButton];
    self.navigationItem.leftBarButtonItem = iLButton;
    [logoButton release];
    [iLButton release];
    
    UIButton *backButton = [UIButton buttonWithType:100];
    [backButton setTitle:@"Zurück" forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(goBack) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *iRButton = [[UIBarButtonItem alloc] initWithCustomView: backButton];
    self.navigationItem.rightBarButtonItem = iRButton;
    [iRButton release];
    
    // init data
    locationArray = [[NSMutableArray alloc] init];
    
    // selected tab
    [myTabBar setSelectedItem:[myTabBar.items objectAtIndex:0]];
    
    // register for update heading notifications
    [[NSNotificationCenter defaultCenter] addObserver: self 
                                             selector: @selector(changedCompass:) 
                                                 name: @"degreeCompassChanged" 
                                               object: nil];
}

- (void)viewDidUnload
{
    //NSLog(@"RADAR -> viewDidUnload");
    [self cleanup];
    
    // unregister for update heading notifications while not visible.
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name: @"degreeCompassChanged"
                                                  object:nil];
    
    [super viewDidUnload];
}

- (void)viewWillAppear:(BOOL)animated
{
    //NSLog(@"RADAR -> viewWillAppear");
    //NSLog(@"RADAR -> viewControllers: %@", self.navigationController.viewControllers);
    
    // save state
    [AppDelegate saveState:1 withViewController:self];
    
    // update tabbar
    [AppDelegate updateTabBarItem:myTabBar withMailValue:-1 andUpdateMute:NO];
    
    // update radar
    [self updateLocation];
} 


- (void)peseudoReload
{
    // update radar
    radarWScanImageView.hidden = NO;
    radarGScanImageView.hidden = NO;
    timer1 = [NSTimer scheduledTimerWithTimeInterval:0.001 target:self selector:@selector(onRadarGScanning) userInfo:nil repeats:YES];
    
    AppDelegate *d = [[UIApplication sharedApplication] delegate];
    
    //NSLog(@"GPS(%f, %f)", d.lat, d.lon);
    
    NSString *postString = [NSString stringWithFormat:@"op=loadLocationList&username=%@&radius=%d&lat=%f&lon=%f",
                            [[NSUserDefaults standardUserDefaults] stringForKey:@"username"],
                            [[[NSUserDefaults standardUserDefaults] stringForKey:@"radius"] intValue], d.lat, d.lon];
    NSData *postData = [postString dataUsingEncoding:NSUTF8StringEncoding];
    NSString *postLength = [NSString stringWithFormat:@"%d", [postString length]];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: [NSURL URLWithString:[[NSUserDefaults standardUserDefaults] stringForKey:@"url_preference"]]];
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setHTTPBody:postData];       
    [request setTimeoutInterval:60.0];
    NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    if (conn) {
        // init data    
        responseData = [[NSMutableData data ] retain];
//        
//        // loading
//        UIWindow *theWindow = [UIApplication sharedApplication].keyWindow;
//        HUD = [[MBProgressHUD alloc] initWithWindow:theWindow];
//        [theWindow addSubview:HUD];
//        HUD.delegate = self;
//        HUD.alpha = 0.02;
//        [HUD show:YES];
    }
    [conn release];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark -
#pragma mark MKAnnotation delegate

- (MKAnnotationView *) mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation {
    
    MAnnotation *annotation1 = annotation;
    
    MKAnnotationView *annView = [[[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"currentloc"] autorelease];
    annView.canShowCallout = NO;
    annView.calloutOffset = CGPointMake(0, 0);
    
    NSString *st = @"";
    if (annotation1.isRoot)
        st = @"gmap_blue_point.png";
    else
        st = @"gmap_green_point.png";
    
    UIImage *pinImage = [UIImage imageNamed:st];
    annView.image = pinImage;
    return annView;
}

-(MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id <MKOverlay>)overlay {
    MapOverlayView *mapOverlayView = [[[MapOverlayView alloc] initWithOverlay:overlay] autorelease];
    
    return mapOverlayView;
}

#pragma mark -
#pragma mark TabBar

- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item {
    [myTabBar setSelectedItem:[myTabBar.items objectAtIndex:0]];
    switch (item.tag) {
        case 0:
            break;
        case 1:
            [[[[self.tabBarController.viewControllers objectAtIndex:2] topViewController] navigationController] popToRootViewControllerAnimated:NO];
            self.tabBarController.selectedIndex = 2;
            break;
        case 2: 
            [[[[self.tabBarController.viewControllers objectAtIndex:3] topViewController] navigationController] popToRootViewControllerAnimated:NO];
            self.tabBarController.selectedIndex = 3;
            break;
        case 3: 
            [AppDelegate updateTabBarItem:myTabBar withMailValue:-1 andUpdateMute:YES];
            break;
        default:
            break;
    }
}

#pragma mark -
#pragma mark NSURLConnectionDelegete

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response 
{
	[responseData setLength:0];
    
    // loading
	HUD.mode = MBProgressHUDModeDeterminate;
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 
{
	[responseData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error 
{
    // loading
    [HUD hide:YES];
    
    // not rotate
    radarGScanImageView.hidden = YES;
    radarWScanImageView.hidden = YES;
    [timer1 invalidate];
    timer1 = nil;
    
    /* Error message */
	UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil 
													message:NSLocalizedString(@"Unknown network error", nil)
												   delegate:self 
										  cancelButtonTitle:NSLocalizedString(@"OK", nil) 
										  otherButtonTitles:nil];
	[alert show];
	[alert release];	
    
    [responseData release];
    responseData = nil;
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection 
{
	NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
    
    [locationArray removeAllObjects];
    [locationArray addObjectsFromArray:[responseString JSONValue]];
    [responseString release];
    
    [self addOnGoogleMap];
    
    radarGScanImageView.hidden = YES;
    radarWScanImageView.hidden = YES;
    [timer1 invalidate];
    timer1 = nil;
    
    [responseData release];
    responseData = nil;
    
    // loading
    [HUD hide:YES];
}

#pragma mark -
#pragma mark MBProgressHUDDelegate methods

- (void)hudWasHidden:(MBProgressHUD *)hud {
    // Remove HUD from screen when the HUD was hidded
    [HUD removeFromSuperview];
    [HUD release];
    HUD = nil;
}

@end
